#
# - Find portaudio
# Find the native PORTAUDIO includes and library
#
#  PORTAUDIO_INCLUDE_DIRS - where to find portaudio.h, etc.
#  PORTAUDIO_LIBRARIES    - List of libraries when using portaudio.
#  PORTAUDIO_FOUND        - True if portaudio found.
#
# For Windows, Portaudio is just  a set of headers, there is no library
# we build an archive ourselves
# So set PORTAUDIO_SRC_DIR and PORT_AUDIO_INCLUDE_DIRS


IF (PORTAUDIO_INCLUDE_DIRS)
  # Already in cache, be silent
  SET(PORTAUDIO_FIND_QUIETLY TRUE)
ENDIF (PORTAUDIO_INCLUDE_DIRS)

INCLUDE(FindWSWinLibs)
FindWSWinLibs("portaudio_.*" "PORTAUDIO_HINTS")

find_package(PkgConfig)
pkg_search_module(PORTAUDIO portaudio-2.0)

FIND_PATH(PORTAUDIO_INCLUDE_DIR portaudio.h
  HINTS
    "${PORTAUDIO_INCLUDEDIR}"
    "${PORTAUDIO_HINTS}/include"
)

SET(PORTAUDIO_NAMES portaudio)
FIND_LIBRARY(PORTAUDIO_LIBRARY NAMES ${PORTAUDIO_NAMES}
  HINTS "${PORTAUDIO_LIBDIR}")

# handle the QUIETLY and REQUIRED arguments and set PORTAUDIO_FOUND to TRUE if
# all listed variables are TRUE
INCLUDE(FindPackageHandleStandardArgs)
IF(WIN32)
  FIND_PACKAGE_HANDLE_STANDARD_ARGS(PORTAUDIO DEFAULT_MSG PORTAUDIO_INCLUDE_DIR)
ELSE(WIN32)
  FIND_PACKAGE_HANDLE_STANDARD_ARGS(PORTAUDIO DEFAULT_MSG PORTAUDIO_LIBRARY PORTAUDIO_INCLUDE_DIR)
ENDIF(WIN32)

IF(PORTAUDIO_FOUND)
  IF(WIN32)
    SET( PORTAUDIO_LIBRARIES "" )
    SET( PORTAUDIO_SRC_DIR "${PORTAUDIO_HINTS}/src" )
    SET( PORTAUDIO_INCLUDE_DIR
      ${PORTAUDIO_INCLUDE_DIR}
      ${PORTAUDIO_SRC_DIR}/common
      ${PORTAUDIO_SRC_DIR}/os/win
    )
  ELSE(WIN32)
    SET( PORTAUDIO_LIBRARIES ${PORTAUDIO_LIBRARY} )
  ENDIF(WIN32)
  SET( PORTAUDIO_INCLUDE_DIRS ${PORTAUDIO_INCLUDE_DIR} )

  # Check for newer PortAudio V19 API
  # http://www.portaudio.com/docs/proposals/018-VersionInformationInterface.html
  IF(WIN32)
    # We only have the newer version on Windows
    SET( PORTAUDIO_API_1 )
  ELSE(WIN32)
    INCLUDE(CheckFunctionExists)
    SET(CMAKE_REQUIRED_INCLUDES ${PORTAUDIO_INCLUDE_DIRS})
    SET(CMAKE_REQUIRED_LIBRARIES ${PORTAUDIO_LIBRARIES})
    CHECK_FUNCTION_EXISTS(Pa_GetVersion HAVE_PA_GETVERSION)
    SET(CMAKE_REQUIRED_INCLUDES "")
    SET(CMAKE_REQUIRED_LIBRARIES "")
    IF(HAVE_PA_GETVERSION)
      # Symbol found, must be the newer V19 API
      SET( PORTAUDIO_API_1 )
    ELSE(HAVE_PA_GETVERSION)
      # Symbol not found, must be the older V18 API
      SET( PORTAUDIO_API_1 1 )
    ENDIF(HAVE_PA_GETVERSION)
  ENDIF(WIN32)
ELSE(PORTAUDIO_FOUND)
  SET( PORTAUDIO_LIBRARIES )
  SET( PORTAUDIO_INCLUDE_DIRS )
  SET( PORTAUDIO_SRC_DIR )
ENDIF(PORTAUDIO_FOUND)

MARK_AS_ADVANCED( PORTAUDIO_LIBRARIES PORTAUDIO_INCLUDE_DIRS PORTAUDIO_SRC_DIR )
